outside = r"py_test\text\image\sx1.png"
inside = r"py_test\text\image\sx2.png"
result_path = r"py_test\text\image\result.png"

io_light_weight = 0.2  # 亮度权重，0-1之间，数越大，暗图越清晰，亮图缺失部分越多，建议为0.4-0.6之间
io_color_weight = 0.7  # 颜色权重，0-1之间，数越大，图片颜色越鲜艳，暗图部分颜色会变得过于突出，建议0-0.5之间

import cv2
import numpy as np

def load_and_preprocess(image_path):
    """加载图像并转为RGBA格式"""
    img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
    if img is None:
        raise ValueError(f"无法读取图像: {image_path}")
    
    # 统一转换为RGBA格式
    if len(img.shape) == 2:  # 灰度图
        return cv2.cvtColor(img, cv2.COLOR_GRAY2RGBA)
    elif img.shape[2] == 3:  # RGB图
        return cv2.cvtColor(img, cv2.COLOR_RGB2RGBA)
    else:  # 已经是RGBA
        return img

def resize_to_match(base_w, base_h, target_w, target_h):
    """计算保持比例的缩放尺寸"""
    scale = max(base_w / target_w, base_h / target_h)
    return (int(target_w * scale), int(target_h * scale))

def process_images(imgA, imgB):
    # 预处理：自动缩放较小图像
    hA, wA = imgA.shape[:2]
    hB, wB = imgB.shape[:2]
    
    # 判断是否需要缩放
    if wA < wB and hA < hB:
        new_size = resize_to_match(wB, hB, wA, hA)
        imgA = cv2.resize(imgA, new_size, interpolation=cv2.INTER_CUBIC)
    elif wB < wA and hB < hA:
        new_size = resize_to_match(wA, hA, wB, hB)
        imgB = cv2.resize(imgB, new_size, interpolation=cv2.INTER_CUBIC)
    
    return imgA, imgB

def create_canvas(img1, img2):
    """创建统一尺寸的画布"""
    h1, w1 = img1.shape[:2]
    h2, w2 = img2.shape[:2]
    max_w = max(w1, w2)
    max_h = max(h1, h2)
    return (
        np.zeros((max_h, max_w, 4), dtype=np.uint8),
        np.zeros((max_h, max_w, 4), dtype=np.uint8)
    )

def paste_center(canvas, image):
    """将图像居中放置到画布"""
    h, w = image.shape[:2]
    canvas_h, canvas_w = canvas.shape[:2]
    x = (canvas_w - w) // 2
    y = (canvas_h - h) // 2
    
    # 处理单通道灰度转四通道RGBA
    if len(image.shape) == 2:
        rgba = cv2.cvtColor(image, cv2.COLOR_GRAY2RGBA)
    else:
        rgba = image
    
    canvas[y:y+h, x:x+w] = rgba
    return canvas

# 主程序流程
try:
    # 读取图像
    imgA = load_and_preprocess(outside)
    imgB = load_and_preprocess(inside)
    
    # 自动缩放处理
    imgA, imgB = process_images(imgA, imgB)
    
    # 创建画布
    canvasA, canvasB = create_canvas(imgA, imgB)
    
    # 将图像居中放置到画布
    canvasA = paste_center(canvasA, imgA)
    canvasB = paste_center(canvasB, imgB)

    # 调整亮度
    canvasA[..., :3] = np.clip(canvasA[..., :3], 255*io_light_weight, 255)  # 提亮
    # canvasA[..., :3] = (255 - (255-canvasA[..., :3]) * (1-io_light_weight)).astype(np.uint8)
    # cv2.imshow("blended", canvasA)
    # cv2.waitKey(0)

    canvasB[..., :3] = (canvasB[..., :3] * io_light_weight).astype(np.uint8)  # 压暗

    
    # 计算透明度
    alpha = 255 - (canvasA[..., 0] - canvasB[..., 0])
    alpha = np.clip(alpha, 1, 255)
    
    # 混合图像
    blended = np.zeros_like(canvasA)
    for c in range(3):
        blended[..., c] = np.clip(
            (canvasA[..., c] * io_color_weight + (canvasB[..., c] * 255.0) / alpha * (1-io_color_weight)),
            0, 255
        ).astype(np.uint8)
    blended[..., 3] = alpha
    
    # 保存结果
    cv2.imwrite(result_path, blended)

except Exception as e:
    print(f"处理出错: {str(e)}")